package com.example.demo.config;


import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;


/*
* 实现统一数据返回的保底类
* 说明：在返回数据之前，监测数据的类型是否为统一的对象，如果不是就封装成统一对象
*
* */


@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Resource
    private ObjectMapper objectMapper;



    /*
    * 返回时true的情况下会调用beforeBodyWrite
    * */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


    /**
     * 对数据格式进行有效的封装，对String类型单独处理
     *
     * */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body instanceof AjaxResult){
            // AjaxResult 格式可以直接返回
            return body;
        }
        if (body instanceof String){
            //使用Jackson转换
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return AjaxResult.success(body);

    }
}







